#!/usr/bin/env python3
"""
 该脚本为 lv_label_set_text 和 lv_span_set_text 函数对应添加
 lv_obj_set_user_data 和 lv_span_set_user_data 函数以便用于国际化
"""

import re
import argparse
import os
import shutil

def process_file(input_file, make_copy):
    # 正则表达式1：匹配带有 _() 的情况
    pattern_with_underscore = re.compile(
        r'^(\s*)'                          # 缩进 (group1)
        r'(lv_(label|span)_set_text\s*\()' # 函数名和左括号 (group2), 类型 (group3)
        r'\s*([\w\->\.]+)\s*,\s*'          # 组件名 (group4)
        r'_\("([^"]+)"\)\s*\)\s*;?'        # 被 _() 包裹的字符串 (group5)
        r'.*'
    )

    # 正则表达式2：匹配不带 _() 的情况
    pattern_without_underscore = re.compile(
        r'^(\s*)'                          # 缩进 (group1)
        r'(lv_(label|span)_set_text\s*\()' # 函数名和左括号 (group2), 类型 (group3)
        r'\s*([\w\->\.]+)\s*,\s*'          # 组件名 (group4)
        r'"([^"]+)"\s*\)\s*;?'             # 直接的双引号字符串 (group5)
        r'.*'
    )

    if make_copy:
        base, ext = os.path.splitext(input_file)
        output_file = f"{base}_modified{ext}"
        shutil.copy2(input_file, output_file)
        file_to_process = output_file
    else:
        output_file = input_file
        file_to_process = input_file + ".tmp"

    with open(input_file, 'r', encoding='utf-8') as f_in, \
         open(file_to_process, 'w', encoding='utf-8') as f_out:

        for line in f_in:
            line = line.rstrip('\n')
            # 先检查带 _() 的情况
            match_with = pattern_with_underscore.match(line)
            if match_with:
                indent = match_with.group(1)
                func_part = match_with.group(2)  # 函数名和左括号，如 "lv_label_set_text("
                widget_type = match_with.group(3) # "label" 或 "span"
                widget_name = match_with.group(4)
                string_id = match_with.group(5)
                
                # 构造新行
                new_line = f"{indent}{func_part}{widget_name}, _(\"{string_id}\"));\n"
                if widget_type == 'label':
                    user_data_line = f"lv_obj_set_user_data({widget_name}, \"{string_id}\")"
                else:
                    user_data_line = f"lv_span_set_user_data({widget_name}, \"{string_id}\")"
                new_line += f"{indent}{user_data_line};  //* add user data"
                f_out.write(new_line + '\n')
                continue

            # 检查不带 _() 的情况
            match_without = pattern_without_underscore.match(line)
            if match_without:
                indent = match_without.group(1)
                func_part = match_without.group(2)  # 函数名和左括号
                widget_type = match_without.group(3)
                widget_name = match_without.group(4)
                string_content = match_without.group(5)
                
                # 构造新行
                new_line = f"{indent}{func_part}{widget_name}, \"{string_content}\");\n"
                if widget_type == 'label':
                    user_data_line = f"lv_obj_set_user_data({widget_name}, NULL)"
                else:
                    user_data_line = f"lv_span_set_user_data({widget_name}, NULL)"
                new_line += f"{indent}{user_data_line};  //* add user data is NULL"
                f_out.write(new_line + '\n')
                continue

            # 无匹配，直接写入原行
            f_out.write(line + '\n')

    if not make_copy:
        os.replace(file_to_process, output_file)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('input_file')
    parser.add_argument('--copy', action='store_true')
    args = parser.parse_args()

    if not os.path.isfile(args.input_file):
        print(f"Error: File {args.input_file} not found")
        exit(1)

    process_file(args.input_file, args.copy)
    print("Processing completed successfully")